class Individual < ActiveRecord::Base
  belongs_to :expense
  def markaspaid
    puts "Marking something as paid. careful."
  	self.update_attributes({:paid => true})
  end
  
  def Individual.consolidate(usera, userb)
    puts "Consolidating..."
    indv_a_owes_b = usera.individuals_owed_to(userb)
  	indv_b_owes_a = userb.individuals_owed_to(usera)
  	
  	a_owes_b = 0
  	b_owes_a = 0
  	
  	for indv in indv_a_owes_b
  		a_owes_b += indv.amount
  		indv.markaspaid
  	end
  	
  	for indv in indv_b_owes_a
  		b_owes_a += indv.amount
  		indv.markaspaid
  	end
  	
  	puts "CONSOLIDATION CALC"
  	puts a_owes_b
  	puts b_owes_a
	
	  #FUTURE - link 'Consolidations' to the newly created Individual
	  
  	if a_owes_b > b_owes_a
  		rem = a_owes_b - b_owes_a
  		puts rem
  	  indv = Individual.create(:payee => userb.id, :payer => usera.id, :amount => rem, :paid => false, :con => true) #1 still owes 2 the remaining balance
  	elsif b_owes_a > a_owes_b
  		rem = b_owes_a - a_owes_b
  		puts rem
  		indv = Individual.create(:payee => usera.id, :payer => userb.id, :amount => rem, :paid => false, :con => true) #2 still owes 1 the remaining balance
  	else
  	end
  end
	
	def Individual.find_where_payer_by_expense(id, expense)
		Individual.find(:all, :order=>"created_at DESC", :conditions => {:payer => id, :expense_id => expense.id, :paid => false})
	end
	
	
	
	def Individual.find_where_payee_by_expense(id, expense)
		Individual.find(:all, :order =>"created_at DESC", :conditions => {:payee => id, :expense_id => expense.id, :paid => false})
	end
	
	
	
	def Individual.paginate_where_payer(id, page)
		Individual.paginate :conditions => {:payer => id}, :order => 'created_at DESC', :per_page => 10, :page => page
	end
	
	def Individual.paginate_where_payee(id, page)
		Individual.paginate :conditions => {:payee => id}, :order => 'created_at DESC', :per_page => 10, :page => page
	end
	
	
end
